import { AccountService } from './../../service/accountService';
import { ServiceManager } from './../../common/serviceFactory/serviceManager';
import * as Koa from 'koa';
import { route, RouteOptionsBase, Tools } from "../../common";
import { AuthenService } from '../../service/authenService';
import { ServiceException } from '../../common/excpetion';
import { UserService } from '../../service/userService';
const authSvr = ServiceManager.Current.GetService<AuthenService>('AuthenService');
const accountSvr = ServiceManager.Current.GetService<AccountService>('AccountService');
const userSvr = ServiceManager.Current.GetService<UserService>('UserService');

class AuthController {
    @route(new RouteOptionsBase('put', '/api/signIn'))
    async signIn(ctx: Koa.Context, next) {
        let reqData: SignInReq = ctx.request.body;
        let account = await accountSvr.GetAccountByUsername(reqData.username);
        if (!account) {
            throw new ServiceException('账号不存在！');
        }
        if (account.password != reqData.password) {
            throw new ServiceException('密码错误!');
        }
        let token = await authSvr.SaveLoginToken(account, ctx.ip);
        let user = await userSvr.GetUserByAccountId(account.id);

        if (user.organizationId != 'global' && reqData.orgId) {
            if (reqData.orgId != user.organizationId) {
                throw new ServiceException('当前单位不存在该人员！');
            }
        }

        ctx.response.body = { account: account, token, user };
        await next();
    }
}

interface SignInReq {
    username: string;
    password: string;
    orgId?: string;
}